class_name CardPile
extends Resource

signal card_pile_size_changed(cards_amout)

@export var cards: Array[Card] = []


func empty() -> bool:
	return cards.is_empty()

#抽牌
func draw_card() -> Card:
	var card = cards.pop_front()
	card_pile_size_changed.emit(cards.size())
	return card

#添加卡牌
func add_card(card: Card):
	# 检查卡牌是否为null
	if card == null:
		print("❌ 错误：尝试添加null卡牌")
		return
	
	cards.append(card)
	card_pile_size_changed.emit(cards.size())

#添加卡牌并创建深度复制
func add_card_copy(card: Card, reset_uses: bool = false):
	# 检查卡牌是否为null
	if card == null:
		print("❌ 错误：尝试复制null卡牌")
		return null
	
	# 创建卡牌的深度复制
	var card_copy: Card = card.duplicate(true)
	
	# 确保每张卡牌都有自己的唯一值
	if card_copy.card_max_repeat_num > 0:
		if reset_uses:
			# 只有在明确要求重置使用次数时才重置
			card_copy.card_current_repeat_num = card_copy.card_max_repeat_num
			print("复制并重置卡牌 %s，设置使用次数为最大值: %d" % [card_copy.id, card_copy.card_current_repeat_num])
		else:
			# 否则保留原卡牌的当前使用次数
			print("复制卡牌 %s，保留当前使用次数: %d" % [card_copy.id, card_copy.card_current_repeat_num])
	
	cards.append(card_copy)
	card_pile_size_changed.emit(cards.size())
	return card_copy

#洗牌
func shuffle() -> void:
	RNG.array_shuffle(cards)

#清空卡牌堆
func clear() -> void:
	cards.clear()
	card_pile_size_changed.emit(cards.size())

#打印数据
func _to_string() -> String:
	var _card_strings: PackedStringArray = []
	for i in range(cards.size()):
		_card_strings.append("%s: %s" % [i+1, cards[i].id])
	return "\n".join(_card_strings)

func duplicate_cards() -> Array[Card]:
	var new_array: Array[Card] = []
	
	for card: Card in cards:
		new_array.append(card.duplicate())
	
	return new_array
